package com.lishe.lishe.lishe.widget;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Interpolator;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lishe.lishe.R;

/**
 * Created by shino on 2017/10/30.
 * 搜索栏
 */

public class SearchBarView extends ViewGroup implements View.OnClickListener {
    public SearchBarView(Context context) {
        super(context);
        initView(context);
    }

    public SearchBarView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public SearchBarView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public SearchBarView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initView(context);
    }

    RelativeLayout normalLayout;
    RelativeLayout searchLayout;
    ImageView normalImage;
    TextView normalText;
    ImageView cancle;
    ImageView searchImage;
    TextView rigthButton;
    EditText editext;

    private void initView(Context context) {
        View v = LayoutInflater.from(context).inflate(R.layout.item_serach_bar, this);
        normalLayout = v.findViewById(R.id.normal_layout);
        searchLayout = v.findViewById(R.id.search_layout);
        normalImage = v.findViewById(R.id.normal_image);
        normalText = v.findViewById(R.id.normal_text);
        cancle = v.findViewById(R.id.cancle);
        cancle.setVisibility(INVISIBLE);
        searchImage = v.findViewById(R.id.search_image);
        rigthButton = v.findViewById(R.id.right_button);
        editext = v.findViewById(R.id.editext);
        rigthButton.setText("取消");
        normalLayout.setOnClickListener(this);
        cancle.setOnClickListener(this);
        rigthButton.setOnClickListener(this);
        final InputMethodManager imm = (InputMethodManager) context.getSystemService(context.INPUT_METHOD_SERVICE);
        editext.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    imm.showSoftInput(editext, 0);
                } else {
                    imm.hideSoftInputFromWindow(editext.getWindowToken(), 0);
                }
            }
        });
        editext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                Log.e("beforeTextChanged", charSequence.toString());
                Boolean isShow = (charSequence.toString().length() > 0);
                isShowCancel(isShow);
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                Boolean isShow = (charSequence.toString().length() > 0);
                isShowCancel(isShow);
                Log.e("onTextChanged", charSequence.toString());
            }

            @Override
            public void afterTextChanged(Editable editable) {
                Log.e("afterTextChanged", editable.toString());
            }
        });
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        /**
         * 获得此ViewGroup上级容器为其推荐的宽和高，以及计算模式
         */
        int count = getChildCount();
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);

        // 计算出所有的childView的宽和高
        measureChildren(widthMeasureSpec, heightMeasureSpec);

    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int count = getChildCount();
        Log.e("count", count + "");
        int height = 0;
        ViewGroup child;
        for (int i = 0; i < count; i++) {
            child = (ViewGroup) getChildAt(i);
            child.layout(0, height, child.getMeasuredWidth(), height + child.getMeasuredHeight());
            height += child.getMeasuredHeight();

        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.normal_layout:
                normalLayout.setVisibility(GONE);
                searchLayout.setVisibility(VISIBLE);
                editext.requestFocus();
                int w0 = normalLayout.getWidth();
                int h0 = normalLayout.getHeight();
                int w1 = normalImage.getWidth();
                int h1 = normalImage.getHeight();
                int w2 = normalText.getWidth();
                int h2 = normalText.getHeight();
                Log.e("w0" + w0, "h0" + h0);
                Log.e("w1" + w1, "h1" + h1);
                Log.e("w2" + w2, "h2" + h2);
                Log.e("w0x" + normalLayout.getLeft(), "h0y" + normalLayout.getTop());
                Log.e("w1x" + normalImage.getLeft(), "h1y" + normalImage.getTop());
                Log.e("w2x" + normalText.getLeft(), "h2y" + normalText.getTop());
                int length = w0 / 2 - (w1 + w2) / 2;
//                animation();
                break;
            case R.id.search_layout:
                normalLayout.setVisibility(VISIBLE);
                searchLayout.setVisibility(GONE);
                break;
            case R.id.cancle:
                Log.e("清空", "开始");
                editext.getText().clear();
                break;
            case R.id.right_button:
                clikRigthButton();
                break;
        }
    }

    private void isShowCancel(Boolean isShow) {
        if (isShow) {
            cancle.setVisibility(VISIBLE);
            rigthButton.setText("搜索");
        } else {
            cancle.setVisibility(INVISIBLE);
            rigthButton.setText("取消");
        }
    }

    private void clikRigthButton() {
        String text = rigthButton.getText().toString();
        if (text.equals("取消")) {
            normalLayout.setVisibility(VISIBLE);
            searchLayout.setVisibility(GONE);
            if (onSearchClicListener != null) {
                onSearchClicListener.onCanclClick();
            }
        } else if (text.equals("搜索")) {
            if (onSearchClicListener != null) {
                onSearchClicListener.onSearchClick(editext, editext.getText().toString());
            }
        }
    }

    /**
     * view的移动动画
     */
    //    AccelerateDecelerateInterpolator 在动画开始与结束的地方速率改变比较慢，在中间的时候加速
//    AccelerateInterpolator  在动画开始的地方速率改变比较慢，然后开始加速
//    AnticipateInterpolator 开始的时候向后然后向前甩
//    AnticipateOvershootInterpolator 开始的时候向后然后向前甩一定值后返回最后的值
//    BounceInterpolator   动画结束的时候弹起
//    CycleInterpolator 动画循环播放特定的次数，速率改变沿着正弦曲线
//    DecelerateInterpolator 在动画开始的地方快然后慢
//    LinearInterpolator   以常量速率改变
//    OvershootInterpolator    向前甩一定值后再回到原来位置

    private ValueAnimator mScrollAnimator;//属性动画
    private boolean isAnimation = false;

    /**
     * refreshview 出现和隐藏的动画
     *
     * @param time
     * @param interpolator
     * @param value
     * @param toValue
     */
    private void startMoveAnimation(final int time, final Interpolator interpolator, int value, int toValue) {
        if (mScrollAnimator == null) {
            mScrollAnimator = new ValueAnimator();
        }
        isAnimation = true;
        //cancel
        mScrollAnimator.removeAllUpdateListeners();
        mScrollAnimator.removeAllListeners();
        mScrollAnimator.cancel();
        //reset new value
        mScrollAnimator.setIntValues(value, toValue);//动画变量从value变到tovalue,要改变的属性在addUpdateListener的监听中实现如setRefreshHeaderContainerHeight函数
        mScrollAnimator.setDuration(time);//动画持续时间
        mScrollAnimator.setInterpolator(interpolator);//动画频率
        mScrollAnimator.addUpdateListener(mAnimatorUpdateListener);//动画监听这个事件在属性的值（setIntValues刷新状态值）更新时执行相应的操作
        mScrollAnimator.addListener(mAnimationListener);//动画状态监听
        mScrollAnimator.start();
    }

    ValueAnimator.AnimatorUpdateListener mAnimatorUpdateListener = new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator valueAnimator) {
            final int height = (Integer) valueAnimator.getAnimatedValue();
        }
    };

    private void animation(View view, float fromXDelta, float toXDelta, float fromYDelta, float toYDelta) {
        Animation animation = new TranslateAnimation(fromXDelta, toXDelta, fromYDelta, toYDelta);
        animation.setDuration(1500);
        view.startAnimation(animation);
    }

    //---------动画状态监听--------------
    Animator.AnimatorListener mAnimationListener = new AnimatorListenerAdapter() {
        @Override
        public void onAnimationStart(Animator animation, boolean isReverse) {
            Log.e("refreshRecyclerView", "onAnimationStart");
            isAnimation = true;
        }

        @Override
        public void onAnimationEnd(Animator animation, boolean isReverse) {
            Log.e("refreshRecyclerView", "onAnimationEnd");
            isAnimation = false;
        }
    };
    //---------------搜索或取消的点击监听----------------
    Onclick onSearchClicListener;

    public interface Onclick {
        void onSearchClick(EditText ed, String text);

        void onCanclClick();
    }

    public void setOnSearchClicListener(Onclick onSearchClicListener) {
        this.onSearchClicListener = onSearchClicListener;
    }
}
